<!--
 * @Description: 用户管理页面 - 列表查询、分页、增删改与角色权限分配
 * @Author: lujq
 * @Date: 2025-08-25
 * @LastEditors: lujq
 * @LastEditTime: 2025-08-25 17:10:00
-->
<template>
  <div class="users-page">
    <el-card class="users-card">
      <template #header>
        <div class="card-header">
          <span class="card-title">用户管理</span>
          <div class="header-actions">
            <el-input v-model="query.keyword" placeholder="搜索用户名/姓名/邮箱/电话" clearable class="w-260" @keyup.enter="handleSearch" />
            <el-select v-model="query.role" placeholder="角色" clearable class="w-160">
              <el-option v-for="r in roleOptions" :key="r" :label="rLabel(r)" :value="r" />
            </el-select>
            <el-select v-model="query.status" placeholder="状态" clearable class="w-120">
              <el-option label="启用" value="active" />
              <el-option label="停用" value="inactive" />
            </el-select>
            <el-button type="primary" @click="handleSearch">查询</el-button>
            <el-button @click="resetQuery">重置</el-button>
            <el-button type="success" @click="openCreateDialog">新增用户</el-button>
            <el-button type="danger" :disabled="!multipleSelection.length" @click="handleBatchDelete">批量删除</el-button>
          </div>
        </div>
      </template>

      <el-table :data="list" v-loading="loading" stripe @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="50" />
        <el-table-column prop="username" label="用户名" min-width="120" />
        <el-table-column prop="name" label="姓名" min-width="120" />
        <el-table-column prop="role" label="角色" min-width="120">
          <template #default="{ row }">{{ rLabel(row.role) }}</template>
        </el-table-column>
        <el-table-column prop="email" label="邮箱" min-width="160" />
        <el-table-column prop="phone" label="电话" min-width="120" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 'active' ? 'success' : 'info'">{{ row.status === 'active' ? '启用' : '停用' }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="lastLoginTime" label="最近登录" width="180">
          <template #default="{ row }">{{ formatDateTime(row.lastLoginTime) }}</template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180">
          <template #default="{ row }">{{ formatDateTime(row.createTime) }}</template>
        </el-table-column>
        <el-table-column label="操作" width="160" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="openEditDialog(row)">编辑</el-button>
            <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          :page-size="pagination.pageSize"
          :current-page="pagination.page"
          :page-sizes="[10, 20, 30, 50]"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑用户对话框 -->
    <el-dialog v-model="dialog.visible" :title="dialog.isEdit ? '编辑用户' : '新增用户'" width="580px">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" placeholder="请输入用户名" :disabled="dialog.isEdit" />
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="form.name" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入电话" />
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select v-model="form.role" placeholder="请选择角色">
            <el-option v-for="r in fullRoleOptions" :key="r" :label="rLabel(r)" :value="r" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio label="active">启用</el-radio>
            <el-radio label="inactive">停用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="!dialog.isEdit" label="初始密码" prop="password">
          <el-input v-model="form.password" placeholder="可不填，默认随机" show-password />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialog.visible = false">取消</el-button>
        <el-button type="primary" :loading="dialog.loading" @click="submitForm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
/****
 * 组件脚本：提供用户列表查询、增删改、角色分配等逻辑
 * 函数：
 * - fetchData: 拉取用户分页数据
 * - handleSearch/resetQuery: 查询与重置
 * - openCreateDialog/openEditDialog: 打开新增/编辑弹窗
 * - submitForm: 提交表单，区分创建或更新
 * - handleDelete/handleBatchDelete: 删除单个或批量
 * - handleSizeChange/handleCurrentChange: 分页切换
 */
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { getUserList, createUser, updateUser, deleteUser, batchDeleteUsers } from '@/api/users'
import type { User } from '@/types'
import { formatDateTime } from '@/utils'

// 列表数据与状态
const loading = ref(false)
const list = ref<User[]>([])
const total = ref(0)
const pagination = reactive({ page: 1, pageSize: 10 })
const query = reactive<{ keyword?: string; role?: string; status?: 'active' | 'inactive' }>({})

// 多选
const multipleSelection = ref<User[]>([])
const handleSelectionChange = (rows: User[]) => {
  multipleSelection.value = rows
}

// 角色选项（从数据中提取 + 默认常用）
const defaultRoles = ['admin', 'manager', 'staff']
const roleOptions = computed(() => {
  const set = new Set<string>(defaultRoles)
  list.value.forEach((u) => u.role && set.add(u.role))
  return Array.from(set)
})
const fullRoleOptions = roleOptions
const rLabel = (r: string) => ({ admin: '管理员', manager: '经理', staff: '销售专员', sales: '销售专员' } as any)[r] || r

// 加载数据
const fetchData = async () => {
  loading.value = true
  try {
    const { data } = await getUserList({
      page: pagination.page,
      pageSize: pagination.pageSize,
      keyword: query.keyword,
      role: query.role,
      status: query.status,
      sortBy: 'createTime',
      sortOrder: 'desc',
    })
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  pagination.page = 1
  fetchData()
}
const resetQuery = () => {
  query.keyword = ''
  query.role = undefined as any
  query.status = undefined as any
  handleSearch()
}

// 新增/编辑
const dialog = reactive({ visible: false, isEdit: false, loading: false })
const formRef = ref<FormInstance>()
const form = reactive<Partial<User> & { password?: string }>({
  username: '',
  name: '',
  email: '',
  phone: '',
  role: 'staff',
  status: 'active',
  password: '',
})

const rules: FormRules = {
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  email: [{ type: 'email', message: '邮箱格式不正确', trigger: ['blur', 'change'] }],
  role: [{ required: true, message: '请选择角色', trigger: 'change' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }],
}

const openCreateDialog = () => {
  dialog.visible = true
  dialog.isEdit = false
  Object.assign(form, {
    username: '',
    name: '',
    email: '',
    phone: '',
    role: 'sales',
    status: 'active',
    password: '',
  })
}

const openEditDialog = (row: User) => {
  dialog.visible = true
  dialog.isEdit = true
  Object.assign(form, { ...row })
}

const submitForm = () => {
  formRef.value?.validate(async (valid) => {
    if (!valid) return
    dialog.loading = true
    try {
      if (dialog.isEdit && form.id) {
        await updateUser(form.id, {
          username: form.username!,
          name: form.name!,
          email: form.email!,
          phone: form.phone!,
          role: form.role!,
          status: form.status as any,
        })
        ElMessage.success('更新成功')
      } else {
        await createUser({
          username: form.username!,
          name: form.name!,
          email: form.email!,
          phone: form.phone!,
          role: form.role!,
          status: form.status as any,
          avatar: '',
          permissions: [],
          password: form.password || undefined,
        } as any)
        ElMessage.success('创建成功')
      }
      dialog.visible = false
      fetchData()
    } finally {
      dialog.loading = false
    }
  })
}

// 删除
const handleDelete = (row: User) => {
  ElMessageBox.confirm(`确认删除用户 “${row.name || row.username}” 吗？`, '提示', { type: 'warning' })
    .then(async () => {
      await deleteUser(row.id)
      ElMessage.success('删除成功')
      fetchData()
    })
    .catch(() => {})
}

const handleBatchDelete = () => {
  if (!multipleSelection.value.length) return
  ElMessageBox.confirm(`确认删除选中的 ${multipleSelection.value.length} 个用户吗？`, '提示', { type: 'warning' })
    .then(async () => {
      const ids = multipleSelection.value.map((i) => i.id)
      await batchDeleteUsers(ids)
      ElMessage.success('批量删除成功')
      fetchData()
    })
    .catch(() => {})
}

// 分页
const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  pagination.page = 1
  fetchData()
}
const handleCurrentChange = (page: number) => {
  pagination.page = page
  fetchData()
}

onMounted(fetchData)
</script>

<style scoped>
.users-card {
  margin-top: 12px;
}
.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.header-actions > * {
  margin-left: 8px;
}
.w-120 { width: 120px; }
.w-160 { width: 160px; }
.w-260 { width: 260px; }
.pagination {
  display: flex;
  justify-content: flex-end;
  margin-top: 12px;
}
</style>